/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.service.plugins;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.tools.ClassToolsUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.entity.*;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.manager.RoleManager;
import com.apache.uct.manager.SysManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.Date;
import java.util.List;

/**
 * description: 角色管理插件
 *
 * @author dyhou 创建时间：2016-8-18
 */
public class RoleActionPluginImpl extends AbstractSuperPlugin {

    private RoleManager roleManager;

    private ProxyManager uctProxyManager;

    private ActGiveManager actGiveManager;

    private OrgManager orgManager;

    private SysManager sysManager;

    private IDao actDao;

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)
     */
    public Object execute(ParamsVo param) throws Exception {
        ResultEntity result = new ResultEntity();
        result.setResult("true");
        String method = String.valueOf(param.getParams("method"));
        if ("save".equals(method)) {
            result = save(result, param);
        } else if ("delete".equals(method)) {
            result = delete(result, param);
        } else if ("roleActData".equals(method)) {
            String iusActData = String.valueOf(param.getParams("ifIus"));
            if (Validator.isNull(iusActData)) {
                result = roleActionData(result, param);
            } else {
                result = iusActionData(result, param);
            }
        } else if ("roleInfo".equals(method)) {
            ParamsVo<Role> vo = new ParamsVo<Role>();
            String roleId = String.valueOf(param.getParams("roleId"));
            vo.setInfoId(roleId);
            result.setEntity(roleManager.getInfoById(vo));
            result.setMessage("查询成功");
        } else if ("saveSys".equalsIgnoreCase(method)) {
            saveSys(result, param);
        } else if ("delSys".equalsIgnoreCase(method)) {

        } else if ("listSys".equalsIgnoreCase(method)) {
            listSys(result, param);
        } else if ("sysInfo".equalsIgnoreCase(method)) {
            ParamsVo<Sys> vo = new ParamsVo<Sys>();
            String sysId = String.valueOf(param.getParams("sysId"));
            vo.setInfoId(sysId);
            result.setEntity(sysManager.getInfoById(vo));
            result.setMessage("查询成功");
        }
        return result;
    }

    private ResultEntity save(ResultEntity result, ParamsVo param) {
        ParamsVo<Role> vo = new ParamsVo<Role>();
        Role item = new Role();
        item = (Role) ClassToolsUtil.getInstance().convert2Bean(param.getParams(), item);
        long times = DateUtils.toLong(new Date());
        String userEname = String.valueOf(param.getParams("nowUserEname"));
        String orgId = String.valueOf(param.getParams("orgId"));
        if (Validator.isNotNull(item.getRoleId())) {//对角色信息修改
            item.setUpdateTime(times);
            item.setUpdateUser(userEname);
            if (Validator.isNull(item.getDelStatus()) && Validator.isNotNull(orgId)) {
                item.setDelStatus(orgId);
                ParamsVo<Org> oVo = new ParamsVo<Org>();
                oVo.setInfoId(item.getDelStatus());
                Org org = (Org) orgManager.getInfoById(oVo);
                item.setRoleRemark(org.getFullCname());
            }
        } else {//添加角色信息
            item.setCreateUser(userEname);
            item.setSysEname("uct");
            String orgParam = item.getDelStatus();
            if (Validator.isNotNull(orgParam)) {
                item.setDelStatus(orgParam);
            }
            if ("1".equals(SystemTools.getInstance().getValue("org_act_switch"))) {
                //String sysFlag = String.valueOf(param.getParams("sysFlag"));
                if (Validator.isNotNull(orgId)) {
                    item.setDelStatus(orgId);
                }
            }
            item.setUpdateCount(0);
            item.setCreateTime(times);
            item.setRoleStatus(1);
            if (Validator.isNotNull(item.getDelStatus())) {
                ParamsVo<Org> oVo = new ParamsVo<Org>();
                oVo.setInfoId(item.getDelStatus());
                Org org = (Org) orgManager.getInfoById(oVo);
                item.setRoleRemark(org.getOrgCname());
            }
            vo.setObj(item);
            vo.setKey("checkRoleEname");
            String flag = String.valueOf(roleManager.execute(vo));
            if ("true".equals(flag)) {
                String synchSub = String.valueOf(param.getParams("synchSub"));
                vo.setParams("orgId", item.getDelStatus());
                vo.setParams("synchSub", synchSub);
            } else {
                result.setMessage("角色标识已存在,操作失败！");
                return result;
            }
        }
        vo.setObj(item);
        ResultMsg msg = super.save(vo, item.getRoleId());
        if ("T".equals(msg.getFlag())) {
            result.setEntity(msg.getFlag());
            result.setMessage(msg.getFlag());
        } else {
            result.setMessage(msg.getFlag());
        }
        return result;
    }

    private ResultEntity delete(ResultEntity result, ParamsVo param) {
        ParamsVo<Role> vo = new ParamsVo<Role>();
        String id = String.valueOf(param.getParams("roleId"));
        if (Validator.isNotNull(id)) {
            vo.setInfoId(id);
            vo.setKey("deleteOrg");
            vo.setParams("infoType", "role");
            String msg = String.valueOf(uctProxyManager.doInvoke(vo));
            if (Validator.isNotNull(msg)) {
                result.setMessage("删除失败！");
                return result;
            }
        } else {
            result.setMessage("请选择要删除的角色！");
        }
        result.setEntity("T");
        result.setMessage("删除角色成功！");
        return result;
    }

    private ResultEntity roleActionData(ResultEntity result, ParamsVo param) {
        String parentId = StrUtil.doNull(String.valueOf(param.getParams("id")), "0");
        String roleId = String.valueOf(param.getParams("roleId"));
        Act actVo = new Act();
        actVo.setFatherId(parentId);
        ParamsVo<Act> vo = new ParamsVo<Act>();
        vo.setObj(actVo);
        String nowOrgId = String.valueOf(param.getParams("nowOrgId"));
        if (Validator.isNotNull(nowOrgId) && "1"
                .equals(SystemTools.getInstance().getValue("org_act_switch"))) {
            vo.setParams("userOrgId", nowOrgId);
            vo.setParams("sysUser",
                    StrUtil.doNull(String.valueOf(param.getParams("nowSysUser")), "0"));//是否为系统用户
        }
        vo.setKey("findActForOrg");
        List<Act> actList = (List<Act>) uctProxyManager.doInvoke(vo);
        ParamsVo<ActGive> agVo = new ParamsVo<ActGive>();
        agVo.setParams("roleId", roleId);
        agVo.setParams("giveType", "role");
        agVo.setKey("GiveListByOrgId");
        List<ActGive> giveList = (List<ActGive>) actGiveManager.execute(agVo);

        JSONArray jary = new JSONArray();
        for (int i = 0; i < actList.size(); i++) {
            Act act = actList.get(i);
            JSONObject jvo = JSONObject.fromObject(act);
            if (act.getSubCount() != null && act.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasGive(giveList, act.getActId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        result.setEntity(jary);
        result.setMessage("查询成功");
        return result;
    }

    private ResultEntity iusActionData(ResultEntity result, ParamsVo param) {
        String parentId = StrUtil.doNull(String.valueOf(param.getParams("id")), "0");
        String iusId = String.valueOf(param.getParams("iusId"));
        Act actVo = new Act();
        actVo.setFatherId(parentId);
        ParamsVo<Act> vo = new ParamsVo<Act>();
        vo.setObj(actVo);
        String nowOrgId = String.valueOf(param.getParams("nowOrgId"));
        if (Validator.isNotNull(nowOrgId) && "1"
                .equals(SystemTools.getInstance().getValue("org_act_switch"))) {
            vo.setParams("userOrgId", nowOrgId);
            vo.setParams("sysUser",
                    StrUtil.doNull(String.valueOf(param.getParams("nowSysUser")), "0"));//是否为系统用户
        }
        vo.setKey("findActForOrg");
        List<Act> actList = (List<Act>) uctProxyManager.doInvoke(vo);

        MethodParam params = new MethodParam("ByObjInfo", "", "", Act.class.getName());
        params.setParams("dyncSql", "select act_id from uct_act_ius where ius_id='" + iusId + "'");
        params.setResultCache(false);
        List giveList = (List) actDao.select(params);

        JSONArray jary = new JSONArray();
        for (int i = 0; i < actList.size(); i++) {
            Act act = actList.get(i);
            JSONObject jvo = JSONObject.fromObject(act);
            if (act.getSubCount() != null && act.getSubCount() > 0) {
                jvo.put("state", "closed");
            } else {
                jvo.put("state", "opened");
            }
            String hasGive = hasGiveIus(giveList, act.getActId()) ? "T" : "F";
            jvo.put("hasGive", hasGive);
            jary.add(jvo);
        }
        result.setEntity(jary);
        result.setMessage("查询成功");
        return result;
    }

    /**
     * 判断是否包含该权限值
     *
     * @param giveList 分配的权限值
     * @param actId 权限值id
     * @return boolean
     */
    protected boolean hasGiveIus(List giveList, String actId) {
        if (Validator.isEmpty(giveList))
            return false;
        for (int j = 0; j < giveList.size(); j++) {
            String give = String.valueOf(giveList.get(j));
            if (actId.equals(give)) {
                return true;
            }
        }
        return false;
    }

    private void listSys(ResultEntity result, ParamsVo param) {
        ParamsVo<Sys> vo = new ParamsVo<Sys>();
        Sys item = new Sys();
        item = (Sys) ClassToolsUtil.getInstance().convert2Bean(param.getParams(), item);
        String pageSize = Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "");
        String pageIndex = Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "");
        vo.setObj(item);
        if (Validator.isNotNull(pageSize)) {
            vo.setParams("pageIndex", pageSize);
            vo.setParams("pageSize", pageSize);
            Page pageList = sysManager.getPageInfo(vo);
            result.setEntity(pageList);
        } else {
            result.setEntity(sysManager.getList(vo));
        }

        result.setMessage("查询成功");
    }

    private void saveSys(ResultEntity result, ParamsVo param) {
        ParamsVo<Sys> vo = new ParamsVo<Sys>();
        Sys item = new Sys();
        item = (Sys) ClassToolsUtil.getInstance().convert2Bean(param.getParams(), item);
        long times = DateUtils.toLong(new Date());
        if (Validator.isNotNull(item.getSysId())) {//对系统信息修改
            item.setUpdateTime(times);
            vo.setObj(item);
            boolean mark = sysManager.editInfo(vo);
            if (!mark) {
                result.setMessage("系统信息修改失败！");
                return;
            }
            result.setEntity(mark);
        } else {//添加系统信息
            item.setCreateTime(times);
            vo.setObj(item);
            vo.setKey("checkSysEname");
            String flag = String.valueOf(sysManager.execute(vo));
            if ("true".equals(flag)) {
                String id = sysManager.saveInfo(vo);
                if (Validator.isNull(id)) {
                    result.setMessage("系统信息添加失败！");
                    return;
                }
                result.setEntity(id);
            } else {
                result.setMessage("该系统标识已经存在，操作失败！");
                return;
            }
        }
        result.setMessage("该系统标识已经存在，操作失败！");
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see com.apache.uct.service.plugins.AbstractSuperPlugin#getBaseManager()
     */
    protected BaseManager getBaseManager() {
        return roleManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public void setUctProxyManager(ProxyManager uctProxyManager) {
        this.uctProxyManager = uctProxyManager;
    }

    public void setActGiveManager(ActGiveManager actGiveManager) {
        this.actGiveManager = actGiveManager;
    }

    public void setOrgManager(OrgManager orgManager) {
        this.orgManager = orgManager;
    }

    public void setSysManager(SysManager sysManager) {
        this.sysManager = sysManager;
    }

    public void setActDao(IDao actDao) {
        this.actDao = actDao;
    }
}
